package com.jd.org.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.org.domain.Department;
import com.jd.org.mapper.DepartmentMapper;
import com.jd.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


//    @Override
//    @Transactional
//    public void save(Department department) {
//        departmentMapper.save(department);
//    }
//
//    @Override
//    @Transactional
//    public void remove(Long id) {
//        departmentMapper.remove(id);
//    }
//
//    @Override
//    @Transactional
//    public void update(Department department) {
//        departmentMapper.update(department);
//    }
//
//    @Override
//    public Department loadById(Long id) {
//        return departmentMapper.loadById(id);
//    }
//
//    @Override
//    public List<Department> loadAll() {
//        return departmentMapper.loadAll();
//    }
//
//    @Override
//    public PageList<Department> queryPage(DepartmentQuery departmentQuery) {
//        // 查询总条数
//        Integer totals = departmentMapper.queryPage(departmentQuery);
//        if (totals == 0){
//            return new PageList<>();
//        }
//
//        // 分页查询
//        List<Department> date = departmentMapper.queryData(departmentQuery);
//        return new PageList<>(date,totals);
//    }
//
//    @Override
//    public void patchRemove(List<Long> ids) {
//        departmentMapper.patchRemove(ids);
//    }

    @Override
    public List<Department> deptTree() {
        // 将所有的部门添加的Map中
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department> map = new HashMap<>();
        // 将每一个部门的id和对象保存在Map
        for (Department department:departments){
            map.put(department.getId(),department);
        }

        // 查询部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department: departments){
        // 如果没有父id - 顶级部门
            if (department.getParent_id()==null){
                deptTree.add(department);
            }else {
                // 获取父部门id
                Long parent_id = department.getParent_id();
                // 获取父部门
                Department parentDept = map.get(parent_id);
                if(parentDept != null){
                    // 将自己添加到父部门的Children中去
                    parentDept.getChildren().add(department);
                }

            }
        }


        return deptTree;
    }



}
